package pre.liuxl.blog.repository;

import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;
import pre.liuxl.blog.entity.Permission;
import pre.liuxl.blog.entity.RolePermission;
import pre.liuxl.blog.entity.UserRole;
import pre.liuxl.blog.utils.HibernateSessionFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by liuxuanlong on 2018/6/23.
 */
@Repository
public class PermissionRepository {
    @Autowired
    HibernateTemplate hibernateTemplate;

    public Permission findById(Integer permissionId) {
        return hibernateTemplate.get(Permission.class, permissionId);

    }

    public List<Permission> findByUserId(Integer userId) {
        List<Permission> permissionList = new ArrayList<>();
        Session session = HibernateSessionFactory.getSession();
        session.beginTransaction();
        Query query = session.createQuery("from UserRole userRole where userRole.userId=?1");
        query.setParameter(1, userId);
        List<UserRole> userRoleList = query.getResultList();
        for (UserRole userRole : userRoleList) {
            Query query1 = session.createQuery("from RolePermission  rp where rp.roleId=?1");
            query1.setParameter(1, userRole.getRoleId());
            List<RolePermission> rolePermissionList = query1.getResultList();
            for (RolePermission rolePermission : rolePermissionList) {
                Query query2 = session.createQuery("from Permission p where p.id=?1");
                query2.setParameter(1, rolePermission.getPermissionId());
                permissionList = query2.getResultList();

            }
        }
        session.getTransaction().commit();
        session.close();
        return permissionList;
    }
}
